package com.sakura.hk.sakura.springboot.plugin.task;

import com.sakura.hk.sakura.springboot.plugin.SakuraExtension;
import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.internal.AbstractTask;
import org.gradle.api.tasks.TaskAction;

import java.io.File;

/**
 * 清理缓存
 *
 * @Author: 贺坤
 * @Date: 2021/7/13 16:26
 */
public class ClearCache extends DefaultTask {
    /**
     * 当前任务名称
     */
    public static final String MY_TASK_NAME = "clearCache";
    /**
     * 缓存目录
     */
    private File cacheDir;
    /**
     * 缓存目录名称
     */
    private String cacheName;
    /**
     * 是否删除缓存
     */
    private Boolean delCache;

    @TaskAction
    public void action() {
        init();
        if (delCache) {
            // 删除缓存目录
            File cacheFile = new File(cacheDir, cacheName);
            getProject().delete(cacheFile);
        }
    }


    public static AbstractTask foundMyTask(Project project) {
        ClearCache task = project.getTasks().create(MY_TASK_NAME, ClearCache.class);
        task.dependsOn(GenerateNewBuild.MY_TASK_NAME);
        task.setDescription("删除缓存目录");
        return task;
    }

    private void init() {
        SakuraExtension sakuraExtension = getProject().getExtensions().getByType(SakuraExtension.class);
        this.cacheDir = sakuraExtension.getCacheDir();
        this.cacheName = sakuraExtension.getCacheName();
        this.delCache = sakuraExtension.getDelCache();
    }
}
